package com.general;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.Objects;

/**
 * @description: 查询天气数据服务类
 * @author: general
 * @version: 1.0
 * @create: 2022-04-10 16:56
 **/
public class WeatherService {

    public  String getCityWeather(String city) throws Exception {
        String url = "http://wthrcdn.etouch.cn/weather_mini?city=" + city;
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();
        final Call call = okHttpClient.newCall(request);
        Response response = call.execute();
        String ret =  response.body().string();
        System.out.println("查询天气数据：" + ret);
        return ret;
    }

    public  String getCityWeatherCached(String city, String mapName, HazelcastInstance instance) throws Exception {
        IMap map = instance.getMap(mapName);
        if(Objects.nonNull(map) && Objects.nonNull(map.get(city))){
            Object o = map.get(city);
            System.out.println("查询缓存天气数据 ：" + o);
            return (String) map.get(city);
        }
        String url = "http://wthrcdn.etouch.cn/weather_mini?city=" + city;
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();
        final Call call = okHttpClient.newCall(request);
        Response response = call.execute();
        String ret =  response.body().string();
        map.put(city, ret);
        System.out.println("查询天气数据：" + ret);
        return ret;
    }
}
